<?php

Class Controller_Tag Extends Controller_Base {
	function index(){
		echo "Tag";
	}
	
	public function new_(){
		if(!User::checkAccess("admin"))die('Ошибка доступа');
		if(isset($_POST['form'])){
			$skin['html'] 	= Tag::getViewData("empty","","new");
			$skin['title'] 	= 'Создание ключевых слов';
			
			$skin['html']	= "<form id='new_tag_form'>".$skin['html']."</form>".
			"<div class='p5 ct_'><a class='but' data-url='tag/new_' data-opt='{".'"action":"submit","icon":"disk"'."}'>Сохранить</a></div>";
			echo json_encode($skin);
		}else{
			$v = Tag::validateAll("", $_POST['tags']);
			if($v['state']) {
				Tag::create("",$_POST['tags'],"",true);
			 	$res 	= array("state" => true, "msg" => "Создание новых ключевых слов выполнено!");
				echo json_encode($res);
			} else {
				echo json_encode($v);
			}
		}
	}
	
	public function delete(){
		if(!User::checkAccess("admin"))die('Ошибка доступа');
		if(isset($_POST['id'])){
			$sql 		= "delete from `tag` where `reports`=\"\" and (".preg_replace("/^or/i","",str_replace(","," ",preg_replace("/([^,]+)/i", "or id='$1'", $_POST['id']))).")";
			DB::exec_($sql);
		}
	}
	
	public function grid(){
		$page 	= $_POST['page']; // get the requested page
		$limit 	= $_POST['rows']; // get how many rows we want to have into the grid
		$sidx 	= $_POST['sidx']; // get index row - i.e. user click to sort
		$sord 	= $_POST['sord']; // get the direction
		if(!$sidx) $sidx =1;
		
		$result = Tag::get(DB::$db,"",-1,"count(*) as count","");
		$count 	= $result[0]['count'];
		
		if( $count >0 ) {
			$total_pages = ceil($count/$limit);
		} else {
			$total_pages = 0;
		}
		if ($page > $total_pages) $page=$total_pages;
		$start 	= $limit*$page - $limit; // do not put $limit*($page - 1)
		$SQL 	= "SELECT * from tag ORDER BY $sidx $sord LIMIT $start , $limit";
		$result = DB::query( $SQL );
		
		$responce->page 		= $page;
		$responce->total 		= $total_pages;
		$responce->records 		= $count;
		$i=0;
		foreach($result as $i=> $row){
			$row['reports']				= "";
			$comma 						= "";
			$author 					= Person::get("",$row['author']);
			$fio 						= Person::getFio($author);
		    $responce->rows[$i]['id']	= $row['id'];
		    $responce->rows[$i]['cell']	= array($row['name'],$fio);
		}        
		echo json_encode($responce);
	}
	
	function autocomplete(){
		$d   	= $_POST;
		$res 	= array();
		$limit	= isset($d['maxRows'])? $d['maxRows']:-1;
		$name 	= isset($d['name_startsWith'])? $d['name_startsWith']:"";
		if($limit>0&&$name!=""){
			$sql = 'select `name` as `label`,`id` as `name` from `tag` where `name` like "%'.$name.'%" order by `name` limit '.$limit;	
			try{
				$r =  DB::query($sql);
				echo json_encode($r);
			} catch(PDOException $e) {
				$data['msg'] = "Error: " . $e -> errorInfo() . " sql: " . $sql;
				$data['state'] = false;
				echo json_encode($data);
			}
		}
	}	
}

?>